<template>
    <el-main style="padding: 0px 20px">
      <el-row style="margin:20px 0px">
        <my-Search :searchOption="searchType" @onSearch="getSearchContent"></my-Search>
        <my-Search :searchWay="true" :inputPlaceholder="'器材名称'" @onSearch="getEquipmentSearchContent"></my-Search>
        <el-date-picker
          v-model="choiceDateTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="归还开始日期"
          end-placeholder="归还结束日期"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          @blur="choiceDate"
          @change="choiceDate"
          >
        </el-date-picker>
        <el-button icon="el-icon-refresh-left" style="margin-left:10px" type="primary" @click="getAllEquipmentRent">刷新</el-button>
      </el-row>

      <el-table
        :height="tableHeight"
        :data="equipmentRentData"
        border
        stripe
        row-key="id"
      >
      <el-table-column type="expand" width="55">
        <template slot-scope="scope">
          <el-row style="margin:10px 50px" :gutter="20" >
            <el-col :span="8">
              <el-descriptions class="expandCard" title="具体租借信息" :column="3">
                  <el-descriptions-item label="租借器材">{{scope.row.name}}</el-descriptions-item>
                  <el-descriptions-item label="器材类型">{{scope.row.label}}</el-descriptions-item>
                  <el-descriptions-item label="租借价格">{{'¥ '+scope.row.rentCost+'/时'}}</el-descriptions-item>
                  <el-descriptions-item label="存放位置" :span="3">{{scope.row.local}}</el-descriptions-item>
                  <el-descriptions-item label="订单编号" :span="2">{{scope.row.no}}</el-descriptions-item>
                  <el-descriptions-item label="使用积分" :span="1">{{scope.row.point}}</el-descriptions-item>
                  <el-descriptions-item label="租借时间" :span="3">{{scope.row.getTime+'~'+scope.row.backTime}}</el-descriptions-item>
                  <el-descriptions-item v-if="scope.row.status==3||scope.row.status==4" label="归还时间" :span="3">{{scope.row.updateTime}}</el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="5">
              <el-descriptions class="expandCard" title="租借用户信息" :column="1">
                  <el-descriptions-item label="学号/工号">{{scope.row.nid}}</el-descriptions-item>
                  <el-descriptions-item label="姓名">{{scope.row.username}}</el-descriptions-item>
                  <el-descriptions-item label="联系方式">{{scope.row.phone}}</el-descriptions-item>
                  <el-descriptions-item label="所属组织">{{scope.row.deptName}}</el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column width="150px" prop="nid" align="center" label="学号/工号"></el-table-column>
      <el-table-column width="120px" prop="username" align="center" label="姓名"></el-table-column>
      <el-table-column width="150px" prop="phone" align="center" label="联系方式"></el-table-column>
      <el-table-column prop="name" align="center" label="租借器材" show-overflow-tooltip></el-table-column>
      <el-table-column width="90px" prop="number" align="center" label="租借数量"></el-table-column>
      <el-table-column width="180px" prop="cost" align="center" label="租借花费">
        <template slot-scope="scope">
          {{scope.row.cost | showCost}}
        </template>
      </el-table-column>
      <el-table-column width="180px" prop="getTime" align="center" label="前来领取时间"></el-table-column>
      <el-table-column sortable width="120px" prop="times" align="center" label="租借时长">
        <template slot-scope="scope">
          {{scope.row.times | showTime}}
        </template>
      </el-table-column>
      <el-table-column width="180px" prop="backTime" align="center" label="应归还器材时间"></el-table-column>
      <el-table-column
        prop="status"
        align="center"
        label="租借状态"
        width="260px"
        :filters="statusArr"
        :filter-method="statusFilterHandler"
      >
        <template slot-scope="scope">
          <el-row type="flex" justify="space-around" align="middle">
            <el-input
              maxlength="4"
              style="margin:1px 14px 2px 14px"
              ref="inputRef" v-if="scope.row.onclick"
              placeholder="请输入用户提供的领取码"
              v-model="comInput"
              @keyup.enter.native="$event.target.blur"
              @blur="blurInput(scope.row)"
            ></el-input>
            <el-col v-if="!scope.row.onclick" :span="statusrow(scope.row)">
            <el-alert
              :title="scope.row.status | rentStatus(true,statusArr)"
              :type="scope.row.status | rentStatus(false,statusArr)"
              show-icon
              :closable="false"
            />
            </el-col>
            <!-- 用户领取 由1变2 -->
            <el-col v-if="hasPerm('equipment:equipmentrent:check')&&!scope.row.onclick&&scope.row.status==1" :span="2" >
              <el-button type="success" size="mini" icon="el-icon-check" :disabled="canGetEQRent(scope.row.getTime)" circle @click="checkCode(scope.row)"></el-button>
            </el-col>
            <!-- 用户按时归还 由2变3 -->
            <!-- 用户超时归还 由10变4 -->
            <el-col v-if="hasPerm('equipment:equipmentrent:confirmback')&&!scope.row.onclick&&scope.row.status==2||hasPerm('equipment:equipmentrent:confirmback')&&scope.row.status==10" :span="2" >
              <el-button type="warning" size="mini" icon="el-icon-finished" circle @click="conBack(scope.row)"></el-button>
            </el-col>
            <!-- 撤销租借 由1 or 0 变8 -->
            <el-col v-if="hasPerm('equipment:equipmentrent:cancel')&&!scope.row.onclick&&scope.row.status==1||scope.row.status==0" :span="2">
              <el-button type="danger" size="mini" icon="el-icon-close" circle @click="cancelRent(scope.row)"></el-button>
            </el-col>
            <!-- 允许用户缴纳超时费用 由6变9 -->
            <el-col v-if="hasPerm('equipment:equipmentrent:allowpayment')&&!scope.row.onclick&&scope.row.status==6" :span="2">
              <el-button type="danger" size="mini" icon="el-icon-thumb" circle @click="conCom(scope.row)"></el-button>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <pagination
      ref="pagination"
      @pagination="getPagination"
      :total="parseInt(totalPage)"
      :page="parseInt(searchCondition.page)"
      :limit="parseInt(searchCondition.pageSize)"
      :pageSizes="paginationSize"
      ></pagination>
  </el-main>
</template>

<script>
import {
  getAllEquipmentRentApi,
  editRentStatusApi,
} from "@/api/equipment";
import mySearch from "@/components/MySearch/index";
import pagination from "@/components/Pagination/index";
  export default {
    components: {  mySearch, pagination},
    data(){
      return{
        comInput:'',
        statusArr:[
          // 租借状态（0：待支付，1：待提取，2：待归还，3：按时归还，4：超时归还，5：未支付取消，6：未归还，7：用户取消，8：管理员取消）
          {text: '待支付租借费用', value: 0,type:'info'},
          {text: '待用户领取', value: 1,type:'warning'},
          {text: '租借中待归还', value: 2,type:'warning'},
          {text: '用户已按时归还', value: 3,type:'success'},
          {text: '用户超时归还', value: 4,type:'success'},
          {text: '未支付费用失效', value: 5,type:'info'},
          {text: '用户超时未归还', value: 6,type:'error'},
          {text: '用户取消失效', value: 7,type:'info'},
          {text: '管理员取消失效', value: 8,type:'info'},
          {text: '待用户支付超时费用', value: 9,type:'warning'},
          {text: '已支付超时费用', value: 10,type:'warning'},
        ],
        equipmentRentData:[],
        tableHeight:0,
        searchCondition :{
          name:'',
          nid:'',
          username:'',
          phone:'',
          startTime:'',
          endTime:'',
          page: 1,
          pageSize: 10,
        },
        //分页容量
        paginationSize: [5,10,30,50,100,200],
        //筛选项
        searchType:[{label:"订单号",value:"0"},{label:"学号/工号",value:"1"},{label:"用户姓名",value:"2"},{label:"电话号码",value:"3"}],
        //查询返回 总记录数
        totalPage: 0,
        choiceDateTime:'',
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '未来七天',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '未来一个月',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      }
    },
    created(){
      this.getAllEquipmentRent();
    },
    mounted() {
      this.$nextTick(() => {
        //有页码区就高度多-120
        this.tableHeight = window.innerHeight - 170 - 120;
      })
      //每一分钟自动刷新一次
      this.refreshData=setInterval(()=>{
        this.getAllEquipmentRent()
      },1000*60);
    },
    //生命周期若已设置定时器，需清空定时器beforeDestroy()
    beforeDestroy(){
      clearInterval(this.refreshData);
      this.refreshData=null;
    },
    methods:{
      //状态样式
      statusrow(row){
        if(row.status==1&&this.hasPerm('equipment:equipmentrent:check')||row.status==1&&this.hasPerm('equipment:equipmentrent:cancel')){
          //处于 1 可 验证 与 撤销
          return 15
        }else if(row.status==0&&this.hasPerm('equipment:equipmentrent:cancel')){
          //处于 0 可 撤销
          return 17
        }else if(row.status==2&&this.hasPerm('field:fieldBook:cancel')){
          //处于2 可 正常归还
          return 17
        }else if(row.status==6&&this.hasPerm('equipment:equipmentrent:confirmback')){
          //处于6 可 允许用户缴纳超时费用
          return 17
        }else if(row.status==10&&this.hasPerm('equipment:equipmentrent:allowpayment')){
          //处于10 可 超时归还
          return 17
        }else{
          return 21
        }
      },
      //
      async conCom(row){
        let confirm = await this.$myconfirm("确定用户将支付超时费用？");
        if (confirm) {
          this.changeStatus(row,9);
        }
      },
      //
      async conBack(row){
        let confirm = await this.$myconfirm("确定用户已返还器材？");
        if (confirm) {
          let nowtime = new Date().getTime();
          let backtime =  new Date(row.backTime).getTime();
          if(nowtime>backtime){
            //超时
            this.changeStatus(row,4);
          }else{
            //按时
            this.changeStatus(row,3);
          }
        }
      },
      //撤销提示
      async cancelRent(row){
        let confirm = await this.$myconfirm("确定撤销租借吗？");
        if (confirm) {
          this.changeStatus(row,8);
        }
      },
      //点击到场确认按钮
      checkCode(row){
        //显示输入框
        this.$set(row,'onclick',true)
        //聚焦输入框
        this.$nextTick(() => {
          if(row.onclick){
            this.comInput = '';
            this.$refs.inputRef.focus()
          }
        })
      },
      //失焦触发
      blurInput(row){
        if(this.comInput.length==4){
          if(this.comInput==row.code){
            this.changeStatus(row,2);
          }else{
            this.$message.error("租借码错误！")
          }
        }else if(this.comInput.length>0){
          this.$message.info("请输入四位数字的租借码")
        }
        this.$set(row,'onclick',false)
      },
      //更改租借状态记录
      async changeStatus(row,statusCode){
        let parm ={
          id:row.id,
          oid:row.oid,
          eid:row.eid,
          number:row.number,
          status: statusCode,
          version: row.version
        }
        let res = await editRentStatusApi(parm);
        if(res&&res.code==200){
          this.$message.success(res.msg);
          this.getAllEquipmentRent();
        }
      },
      //日期范围查询
      choiceDate(){
        if(this.choiceDateTime!=null){
          this.searchCondition.startTime = this.choiceDateTime[0];
          this.searchCondition.endTime = this.choiceDateTime[1];
        }else{
          this.searchCondition.startTime = '';
          this.searchCondition.endTime = '';
        }
        this.getAllEquipmentRent();
      },
      //器材租借信息查询
      getEquipmentSearchContent(val){
        this.searchCondition.name = val;
        this.getAllEquipmentRent();
      },
      //租借人信息内容查询
      getSearchContent(val,type){
        switch (type) {
          case '0':
            this.searchCondition.no = val;
            this.searchCondition.nid = '';
            this.searchCondition.username = '';
            this.searchCondition.phone = '';
            break;
          case '1':
            this.searchCondition.no = '';
            this.searchCondition.nid = val;
            this.searchCondition.username = '';
            this.searchCondition.phone = '';
            break;
          case '2':
            this.searchCondition.no = '';
            this.searchCondition.nid = '';
            this.searchCondition.username = val;
            this.searchCondition.phone = '';
            break;
          case '3':
            this.searchCondition.no = '';
            this.searchCondition.nid = '';
            this.searchCondition.username = '';
            this.searchCondition.phone = val;
            break;
          default:
            this.searchCondition.no = '';
            this.searchCondition.nid = '';
            this.searchCondition.username = '';
            this.searchCondition.phone = '';
            break;
        }
        this.getAllEquipmentRent();
      },
      //分页查询getPagination
      getPagination(val){
        this.searchCondition.page = val.page;
        this.searchCondition.pageSize = val.limit;
        this.getAllEquipmentRent();
      },
      //查询
      async getAllEquipmentRent(){
        let res = await getAllEquipmentRentApi(this.searchCondition);
        if(res&&res.code==200){
          this.totalPage = res.data.total;
          this.equipmentRentData = res.data.list;
        }
      },
      //表格租借状态过滤
      statusFilterHandler(value, row, column){
        const property = column['property'];
        return row[property] === value;
      },
      //是否可点击领取
      canGetEQRent(beginTime){
        let d = new Date(beginTime).getTime()-10*60*1000;
        let n = new Date().getTime();
        if(n>=d){
          return false;
        }
        return true;
      }
    },
    filters:{
      rentStatus(val,flag,arr){
        if(flag){
          return arr[val].text
        }else{
          return arr[val].type
        }

      },
      showCost(val){
        if(val==0) {
          return '免费'
        }else{
          return val+'元'
        }
      },
      showTime(val){
        if(val>=24){
          let t = val%24;
          let d = Math.floor(val/24);
          if(t!=0){
            return d+' 天 '+t+' 小时'
          }else{
            return d+' 天'
          }
        }else{
          return val+' 小时'
        }
      },
    }
  }
</script>

<style lang="scss" scoped>
  .expandCard{
    padding: 16px 20px 10px 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
</style>
